로딩 중이에요... 🐣
[코담]
웹개발·실전 프로젝트·AI까지, 파이썬·장고의 모든것을 담아낸 강의와 개발 노트
pandas Part5 머신러닝 모델 웹 앱으로 배포 | ✅ 편저: 코담 운영자
📖 데이터 분석의 시작, Pandas 완전 정복 - Part 5: 머신러닝 모델 웹 앱으로 배포하기
✨ 서론: 모델을 웹 서비스로 만들기
앞선 Part 4에서 Scikit-learn으로 Titanic 생존자 예측 모델을 구축했습니다. 이번 파트에서는 이 모델을 웹 애플리케이션으로 배포하여 사용자 입력으로 생존 여부를 실시간 예측하는 서비스를 만들어봅니다.
💡 실무 팁: Flask 또는 FastAPI는 Python 기반 머신러닝 모델 웹 배포에 가장 많이 사용됩니다.
🛠️ Step 1: 필요한 라이브러리 설치
pip install flask scikit-learn pandas
📦 Step 2: 모델 저장 및 로드
모델 저장
import joblib
# 모델 저장
joblib.dump(model, 'titanic_model.pkl')
모델 로드
# 다른 스크립트에서 모델 로드
model = joblib.load('titanic_model.pkl')
🌐 Step 3: Flask 앱 기본 구조 만들기
from flask import Flask, request, render_template
import joblib
import numpy as np
app = Flask(__name__)
model = joblib.load('titanic_model.pkl')
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
features = [
int(request.form['Pclass']),
int(request.form['Sex']),
float(request.form['Age']),
float(request.form['Fare']),
int(request.form['SibSp']),
int(request.form['Parch']),
int(request.form['Embarked'])
]
prediction = model.predict([features])
result = '생존' if prediction[0] == 1 else '사망'
return render_template('index.html', prediction_text=f'예측 결과: {result}')
if __name__ == "__main__":
app.run(debug=True)
🖥️ Step 4: HTML 입력 폼 (templates/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titanic 생존자 예측기</title>
</head>
<body>
<h2>Titanic 생존자 예측</h2>
<form action="/predict" method="post">
선실 등급(Pclass): <input type="number" name="Pclass"><br>
성별(Sex: 남=0, 여=1): <input type="number" name="Sex"><br>
나이(Age): <input type="number" step="any" name="Age"><br>
요금(Fare): <input type="number" step="any" name="Fare"><br>
형제자매/배우자 수(SibSp): <input type="number" name="SibSp"><br>
부모/자녀 수(Parch): <input type="number" name="Parch"><br>
탑승항구(Embarked: C=0, Q=1, S=2): <input type="number" name="Embarked"><br>
<input type="submit" value="예측하기">
</form>
<h3>{{ prediction_text }}</h3>
</body>
</html>
🚀 Step 5: 앱 실행 및 테스트
python app.py
웹 브라우저에서 http://127.0.0.1:5000
에 접속하여 Titanic 생존자 예측 웹앱을 테스트합니다.
💡 실무 팁: Heroku, Render, Vercel 등의 플랫폼을 사용하면 Flask 앱을 손쉽게 온라인에 배포할 수 있습니다.
📌 결론 및 확장 아이디어
- 사용자 친화적 UI 추가 (Bootstrap 등)
- FastAPI로 업그레이드하여 더 빠른 응답 처리
- Docker로 컨테이너화 후 클라우드에 배포
🎯 최종 목표: 데이터 분석부터 머신러닝 모델 배포까지 전체 파이프라인 구현 완성!